/**
 *  @file StringWriter.cpp
 */
#include "StringWriter.h"
#include "../common/CppMemPool.h"
#include "../common/UtilFuncT.h"

using namespace cppflib::collections;

namespace cppflib
{

namespace io
{

StringWriter::StringWriter(void)
{
   const sz_t BUFFERSIZE = 256;

   this->pStringBuf = new CFString(static_cast<pcwstr_t>(NULL), 0, BUFFERSIZE);
   cppmempool::Retain(this->pStringBuf);
}

/**
 *  Initialize with a specified buffer size
 */
StringWriter::StringWriter(sz_t internalBufSize)
{
   this->pStringBuf = new CFString(static_cast<pcwstr_t>(NULL), 0, internalBufSize);
   cppmempool::Retain(this->pStringBuf);
}

StringWriter::~StringWriter(void)
{
   cppmempool::Release(this->pStringBuf);
}

void StringWriter::Close()
{
   // not implemented
}

void StringWriter::Flush()
{
   // not implemented
}

void StringWriter::Write(ArrayWChar &buffer)
{
   Write(buffer, 0, static_cast<int>(buffer.GetSize()));
}

void StringWriter::Write(ArrayWChar &buffer, int offset, int count)
{
   if (count < 0 || offset < 0 || offset >= static_cast<int>(buffer.GetSize()))
      return;

   // use the smaller one
   count = cppflib::Min<int>(count, static_cast<int>(buffer.GetSize()) - offset);

   pStringBuf->Append(&(static_cast<pcwstr_t>(buffer.GetRawPtr())[offset]), count);
}

void StringWriter::Write(const CFString &str)
{
   Write(str, 0, str.GetLength());
}

void StringWriter::Write(const CFString &str, int offset, int count)
{
   if (count < 0 || offset < 0 || offset >= str.GetLength())
      return;

   // use the smaller one
   count = cppflib::Min<int>(count, str.GetLength() - offset);

   pStringBuf->Append(&(static_cast<pcwstr_t>(str)[offset]), count);
}

void StringWriter::Write(int c)
{
   *pStringBuf += static_cast<wc_t>(c);
}


/**
 *  Get the internal string buffer
 */
CFString & StringWriter::GetStringBuffer()
{
   return *this->pStringBuf;
}

} // end of namespace io

} // end of namespace cppflib
